<?php

/**
 * @Author: wuchenge
 * @Date:   2021-12-10 17:42:38
 * @Email: ligui0506@126.com
 * @Descript: api 公共控制器
 */
namespace App\Http\Controllers;

use Response;

class ApiController extends Controller
{
    protected $error_code  = 0;
    protected $message     = 'ok';
    protected $failed_code = 1;

    /**
     * [getErrorCode 获取消息码]
     * @return [type] [description]
     */
    public function getErrorCode()
    {
        return $this->error_code;
    }

    /**
     * [getErrorCode 获取消息]
     * @return [type] [description]
     */
    public function getMessage()
    {

        return $this->message;
    }

    /**
     * [setErrorCode 设置消息码 ]
     * @param [type] $status_code [消息码]
     * @param [type] $message [错误消息]
     */
    public function setErrorCode($error_code, $message = '')
    {
        $this->error_code = $error_code;
        if ($message) {
            $this->message = $message;
        }

        return $this;
    }

    /**
     * [response 返回JSON格式数据并添加消息码和消息]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function response($data = [], $message = '')
    {
        // 返回总数据
        $response = [];

        // 返回消息码和消息
        $error_code = $this->getErrorCode();

        if (empty($message)) {
            $message = $this->message;
        }

        $response['data']       = $data;
        $response['message']    = $message;
        $response['error_code'] = $error_code;

        return Response::json($response);
    }

    /**
     * 失败返回
     * @param  integer $code    [description]
     * @param  string  $message [description]
     * @return [type]           [description]
     */
    public function failed($message = '失败,请重试...', $code = 1)
    {

        return $this->setErrorCode($code, $message)->response();
    }
}
